// pages/activityCenter/question.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "满意度调查", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    questionList: [],

    openid: '',
    shareTitle: '',
    shareImg: '',
    id: 0,
    checkBoxList: [],
    type: '', //订单类型 xl 寻麓之旅, activity 活动
    imgMax: 0,
    imgUpNum: 0,
    updataList: []
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },

  //数字输入值
  numTap(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    that.setData({
      ['questionList[' + idx + '].value']: e.detail.value
    });
  },
  reduce(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var num = that.data.questionList[idx].value;
    if (num > 0) {
      num--
    }
    that.setData({
      ['questionList[' + idx + '].value']: num
    });
  },
  add(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var num = that.data.questionList[idx].value;
    num++
    that.setData({
      ['questionList[' + idx + '].value']: num
    });
  },
  //数字输入值
  inputBlur(e) {
    if (parseInt(e.detail.value) >= 0) {
      var that = this;
      var idx = e.currentTarget.dataset.idx;
      that.setData({
        ['questionList[' + idx + '].value']: e.detail.value
      });
    }
  },

  //问答题
  textareaChange(e) {
    let len = e.detail.value.length;
    var idx = e.currentTarget.dataset.idx;
    this.setData({
      ['questionList[' + idx + '].limitNum']: len,
      ['questionList[' + idx + '].value']: e.detail.value
    });
  },

  //单选
  radioChange(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var chooseText = this.data.questionList[idx].chooseList[value - 1].answer;
    if (chooseText == "其他" || chooseText == '其它') {
      that.setData({
        ['questionList[' + idx + '].value']: value,
        ['questionList[' + idx + '].reply']: true
      });
    } else {
      that.setData({
        ['questionList[' + idx + '].value']: value,
        ['questionList[' + idx + '].reply']: false
      });
    }
  },

  //多选题
  checkboxChange(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var value = e.detail.value;
    that.setData({
      checkBoxList: value, //单个选中的值
    })
    var checkBoxList = that.data.checkBoxList;
    if (checkBoxList.indexOf("其他") > -1 || checkBoxList.indexOf("其它") > -1) {
      that.setData({
        ['questionList[' + idx + '].value']: that.data.checkBoxList,
        ['questionList[' + idx + '].reply']: true
      });
    } else {
      that.setData({
        ['questionList[' + idx + '].value']: that.data.checkBoxList,
        ['questionList[' + idx + '].reply']: false
      });
    }
  },

  other(e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx; //这道题中答案的路由
    var row = e.currentTarget.dataset.row; //整个问卷的第几题列表的路由
    var value = e.detail.value;
    console.log(value);
    that.setData({
      [`questionList[${row}].chooseList[${idx}].other`]: value
    });
  },
  getLocalityImg(e) {
    let that = this;
    var idx = e.currentTarget.dataset.idx;
    wx.chooseImage({
      count: that.data.imgUpNum,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFiles = res.tempFiles
        let answer = tempFiles.every(item => {
          return item.size <= parseInt(that.data.imgMax) * 1024 * 1024
        })
        if (answer) {
          var addpic = res.tempFiles.map(el => el.path);

          //保存图片至服务器
          for (var i = 0; i < addpic.length; i++) {
            that.uploadImg(i, addpic[i], idx)
          }
        } else {
          app.showTip("上传图片不能大于" + that.data.imgMax + "M哦");
        }
      }
    })
  },

  //上传图片
  uploadImg(row, imgPath, idx) {
    var that = this;
    wx.showLoading({
      title: '图片上传中...',
      mask: true
    });
    wx.uploadFile({
      url: that.data.baseUrl + "uplpadWdtImg.php", //服务器接口
      method: 'POST',
      filePath: imgPath,
      header: {
        'content-type': 'multipart/form-data'
      },
      name: 'file', //服务器定义的Key值
      formData: {},
      success: function (res) {
        wx.hideLoading();
        console.log(res.data);
        if (res.data) {
          //更新前端显示图片
          var updataList = that.data.questionList[idx].updataList;
          if (!updataList) {
            updataList = [];
          }
          updataList.push(res.data);
          that.setData({
            //['questionList[' + idx + '].updataList']: [...that.data.updataList, ...imgPathAll],
            ['questionList[' + idx + '].updataList']: updataList
          });

          setTimeout(function () {
            console.log(that.data.questionList);
          }, 1500);
        } else {
          app.showTip('服务器保存图片失败,请刷新页面重试');
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
      }
    });
  },

  //删除照片功能与预览照片功能 
  deleteImg(e) {
    let questionList = this.data.questionList;
    let index = e.currentTarget.dataset.index;
    var idx = e.currentTarget.dataset.idx;
    var curUploadImgArr = questionList[idx].updataList;
    var newImgArr = [];
    for (var i = 0; i < curUploadImgArr.length; i++) {
      if (i != index) {
        newImgArr.push(curUploadImgArr[i]);
      }
    }
    this.setData({
      ['questionList[' + idx + '].updataList']: newImgArr
    });
  },
  //预览图片
  previewImg(e) {
    let index = e.currentTarget.dataset.index;
    var idx = e.currentTarget.dataset.idx;
    let questionList = this.data.questionList;
    let img_arr = questionList[idx].updataList;
    wx.previewImage({
      current: img_arr[index],
      urls: img_arr
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //获取寻麓报名id
    var id = options.id;
    var type = options.type;
    //id=7;
    //orderArr.id = 1;
    if (id == 0 || id == '' || id == undefined) {
      app.showTip('抱歉,未获取到报名id哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 1500);
      return;
    } else {
      //赋值id信息
      that.setData({
        id: id,
        type: type
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getMydQuestionPageInfo(res.data.openid, id, type);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getMydQuestionPageInfo(openid, id, type);
    }

    //调用分享
    that.getShareInfo();
  },


  //获取本页数据
  getMydQuestionPageInfo(openid, id, type) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getMydQuestionPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        id: id,
        type: type
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          that.setData({
            questionList: res.data.questionList,
            imgMax: res.data.upImgSize,
            imgUpNum: res.data.upImgNum
          });
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });

  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  //提交所有订单信息
  order() {
    var that = this;


    var questionList = that.data.questionList;
    var answerArr = [];
    var otherArr = [];
    for (var i = 0; i < questionList.length; i++) {
      var questionType = parseInt(questionList[i]['question_type']);
      var value = questionList[i]['value'];
      console.log("questionType:" + questionType + "......." + value)
      if (questionType == 1) {
        //选择题
        if (parseInt(value) <= 0) {
          app.showTip('请选择问题' + (i + 1) + '答案');
          return;
        } else {
          var chooseRow = questionList[i].chooseList[parseInt(value) - 1];
          value = chooseRow.answer;
          var other = chooseRow.other;
          if (value == "其他" || value == "其它") {
            if (other == 'undefined' || other == undefined || (other != undefined && other.trim() == '')) {
              app.showTip('请将问题' + (i + 1) + '的其他选项的内容填写完整');
              return;
            } else {
              //重新更新value的值并且判断other
              if (other) {
                value = value + '[' + other.trim() + ']';
              }
            }
          } else {
            //重新更新value的值并且判断other
            if (other) {
              value = value + '[' + other.trim() + ']';
            }
          }
        }
      } else if (questionType == 2 && parseInt(value) < 0) {
        //数字题
        app.showTip('请填写问题' + (i + 1) + '答案');
        return;
      } else if (questionType == 3 && value == '') {
        //问答题
        app.showTip('请填写问题' + (i + 1) + '答案');
        return;
      } else if (questionType == 4) {
        //多选题
        if (value == '1') {
          app.showTip('请选择问题' + (i + 1) + '答案');
          return;
        } else {
          var newValue = [];
          if (value.indexOf("其他") > -1 || value.indexOf("其它") > -1) {
            //选择了其他
            var checkChooseList = questionList[i].chooseList;
            for (var j = 0; j < value.length; j++) {
              for (var m = 0; m < checkChooseList.length; m++) {
                var other = checkChooseList[m].other;
                var answer = checkChooseList[m].answer;
                if ((answer == '其他' || answer == '其它') && (other == 'undefined' || other == undefined || (other != undefined && other.trim() == ''))) {
                  app.showTip('请将问题' + (i + 1) + '的其他选项的内容填写完整');
                  return;
                }

                if (value[j] == answer && other != undefined && other.trim() != '') {
                  newValue.push((answer + '[' + other.trim() + ']'));
                } else if (value[j] == answer) {
                  newValue.push(answer);
                }
              }
            }
          } else {
            //未选择其他
            var checkChooseList = questionList[i].chooseList;
            for (var j = 0; j < value.length; j++) {
              for (var m = 0; m < checkChooseList.length; m++) {
                var other = checkChooseList[m].other;
                var answer = checkChooseList[m].answer;
                if (value[j] == answer && other != undefined && other.trim() != '') {
                  newValue.push((answer + '[' + other.trim() + ']'));
                } else if (value[j] == answer) {
                  newValue.push(answer);
                }
              }
            }
          }

          value = newValue;
        }
      }

      //单独处理问答题
      if (questionType == 3) {
        var newValue = [];
        newValue.push(value);
        var imgList = questionList[i].updataList;
        if (!imgList) {
          imgList = [];
        }
        newValue.push(imgList);
        value = newValue;
      }

      answerArr.push(value);
    }

    wx.showLoading({
      title: '数据提交中...'
    });


    wx.request({
      url: that.data.baseUrl + 'addMydQuestion.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'answerArr': JSON.stringify(answerArr),
        'id': that.data.id,
        'type': that.data.type
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          app.showTip(res.data.msg);
          //普通活动报名或者交房预约
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1300)
        } else {
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        return;
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})